package com.ourteam.workspace.api;

import java.io.File;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.SystemUtils;

import com.ourteam.frame.web.AbstractTreeNodeBuilder;
import com.ourteam.workspace.dao.IWorkspaceResourceDAO;
import com.ourteam.workspace.dao.WorkspaceResourceDAOQueryBean;
import com.ourteam.workspace.domain.WorkspaceBean;
import com.ourteam.workspace.domain.WorkspaceResourceBean;
import com.ourteam.workspace.service.IWorkspaceService;
import com.ourteam.workspace.service.WorkspaceServiceFactory;

public class WorkspaceResourceNodeBuilder extends AbstractTreeNodeBuilder<WorkspaceBean, WorkspaceResourceBean>
		implements IWorkspaceResourceNodeBuilder {

	private static final IWorkspaceService workspaceService = WorkspaceServiceFactory.getWorkspaceService();

	private File workspaceRootDir;

	public void setWorkspaceRootDir(File workspaceRootDir) {
		this.workspaceRootDir = workspaceRootDir;
	}

	@Override
	public WorkspaceResourceBean[] getTreeNodeObjects(WorkspaceBean parentObject) throws Exception {

		WorkspaceResourceDAOQueryBean queryBean = new WorkspaceResourceDAOQueryBean();

		queryBean.setSortProperty(IWorkspaceResourceDAO.OrderIndex);

		queryBean.createCriteria().andWorkspaceIdEqualTo(parentObject.getId());

		return workspaceService.queryWorkspaceResources(queryBean);
	}

	@Override
	public Object getNodeId(WorkspaceResourceBean childObject) throws Exception {
		return childObject.getId();
	}

	@Override
	public boolean isLeaf(WorkspaceResourceBean childObject) throws Exception {
		return false;
	}

	@Override
	public int getChildCount(WorkspaceResourceBean childObject) throws Exception {
		File file = new File(workspaceRootDir, childObject.getWorkspacePath() + SystemUtils.FILE_SEPARATOR + childObject.getResourcePath());
		return ArrayUtils.getLength(file.list());
	}
	
	
	@Override
	public String getNodeDefineId(WorkspaceResourceBean childObject) throws Exception {
		if ("SOURCE_CODE".equals(childObject.getResourceType())) {
			return "workspaceSourceCodeNode";
		} else if ("DEPEND_LIBARY".equals(childObject.getResourceType())) {
			return "workspaceLibaryNode";
		} 
		else if("WEB_PAGE".equals(childObject.getResourceType())) {
			return "workspaceWebPageNode";
		}
		else if ("WEB".equals(childObject.getResourceType())) {
			return "workspaceWebNode";
		} else if ("FOLDER".equals(childObject.getResourceType())) {
			return "workspaceFolderNode";
		} else {
			return "workspaceResourceNode";
		}

	}

	@Override
	public WorkspaceBean converToParentObject(Object parent) throws Exception {
		return workspaceService.getWorkspaceById(Long.parseLong(parent.toString()));
	}

}
